package com.heartunderblade.rpc.factory;

import com.heartunderblade.rpc.constant.SerializerKeys;
import com.heartunderblade.rpc.service.Serializer;
import com.heartunderblade.rpc.service.impl.HessianSerializer;
import com.heartunderblade.rpc.service.impl.JdkSerializer;
import com.heartunderblade.rpc.service.impl.JsonSerializer;
import com.heartunderblade.rpc.service.impl.KryoSerializer;
import com.heartunderblade.rpc.utils.SpiLoader;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class SerializerFactory {
    //静态块默认加载
//    static {
//        SpiLoader.load(Serializer.class);
//    }

    //线程安全的hashmap，修改静态加载为懒加载。
    private static final ConcurrentHashMap<String, Serializer> CACHE = new ConcurrentHashMap<String, Serializer>();

    private static class DefaultSerializerHolder {
        private static final Serializer DEFAULT_SERIALIZER = new JdkSerializer();
    }

    public static Serializer getDefaultInstance() {
        return DefaultSerializerHolder.DEFAULT_SERIALIZER;
    }

    /**
     * 获取实例
     *
     * @param key
     * @return
     */
    public static Serializer getInstance(String key) {
        if (key == null || key.isEmpty()) {
            return DefaultSerializerHolder.DEFAULT_SERIALIZER;
        }
        // 双检锁实现懒加载和线程安全
        Serializer serializer = CACHE.get(key);
        if (serializer == null) {
            //创建获取SPI的加载,获取序列化器
            synchronized (SerializerFactory.class) {
                SpiLoader.load(Serializer.class);
                serializer = SpiLoader.getInstance(Serializer.class, key);
                if (serializer != null) {
                    //加入缓存
                    CACHE.put(key, serializer);
                } else {
                    //为空返回默认值
                    serializer = getDefaultInstance();
                }
            }
        }
//        return SpiLoader.getInstance(Serializer.class, key);
        return serializer;
    }

}
